// ==UserScript==
// @name         Intercept Comments
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Intercept specific HTTP response and send data to local server.
// @author       You
// @match        https://buyin.jinritemai.com/*
// @match        https://compass.jinritemai.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // 本地服务器的地址
    const localServerURL = 'http://localhost:3000/api/comments';

    // Hook into XMLHttpRequest
    const originalXHROpen = XMLHttpRequest.prototype.open;

    XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
        // 检查是否为目标请求
        if (url.includes('/comment')) {
            console.log('Intercepted Request:', method, url);
            // 通过 onload 事件监听响应
            const originalOnLoad = this.onload;
            this.onload = function(event) {
                // 只有响应状态为 200 时，才处理响应数据
                if (this.status === 200) {
                    console.log('Intercepted Response:', this.responseText);
                    sendDataToServer(JSON.parse(this.responseText))
                }

                // 调用原始 onload 事件处理器
                if (originalOnLoad) {
                    originalOnLoad.call(this, event);
                }
            };
        }

        // 调用原始 open 方法
        originalXHROpen.apply(this, arguments);
    };

    // 函数：将数据发送到本地服务器
    function sendDataToServer(data) {
        fetch(localServerURL, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(result => {
            console.log('Data successfully sent to server:', result);
        })
        .catch(error => {
            console.error('Error sending data to server:', error);
        });
    }
})();
